package com.league.zjxn.main.home

import android.os.Bundle
import android.view.View
import android.webkit.WebSettings
import android.webkit.WebViewClient
import androidx.lifecycle.LifecycleOwner
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.ColorUtils
import com.blankj.utilcode.util.SPStaticUtils
import com.league.zjxn.R
import com.league.zjxn.entity.*
import com.league.zjxn.jetpack.vmodel.SameViewModel
import com.league.zjxn.main.popup.TrendSharePopup
import com.module.lemlin.http.Status
import com.module.lemlin.owner.OwnerAbstractActivity
import com.module.lemlin.owner.OwnerViewModeActivity
import kotlinx.android.synthetic.main.activity_details_trend.*
import org.jsoup.Jsoup
import org.jsoup.nodes.Document
import org.jsoup.select.Elements

class TrendDetailsActivity : OwnerViewModeActivity<SameViewModel>() {

    companion object {
        private const val EXTRA_KEY_TITLE = "EXTRA_KEY_TITLE"
        private const val EXTRA_KEY_TREND = "EXTRA_KEY_TREND"
        private const val EXTRA_KEY_TREND1 = "EXTRA_KEY_TREND1"
        private const val EXTRA_KEY_SEARCH = "EXTRA_KEY_SEARCH"

        fun openCon(title: String? = null, trendData: TrendData) {
            val bundle = Bundle().apply {
                putString(EXTRA_KEY_TITLE, title)
                putSerializable(EXTRA_KEY_TREND, trendData)
            }
            ActivityUtils.startActivity(bundle, TrendDetailsActivity::class.java)
        }

        fun openCon1(title: String? = null, trendData: TrendData1) {
            val bundle = Bundle().apply {
                putString(EXTRA_KEY_TITLE, title)
                putSerializable(EXTRA_KEY_TREND1, trendData)
            }
            ActivityUtils.startActivity(bundle, TrendDetailsActivity::class.java)
        }

        fun openCon2(title: String? = null, homeSearch: HomeSearch) {
            val bundle = Bundle().apply {
                putString(EXTRA_KEY_TITLE, title)
                putSerializable(EXTRA_KEY_SEARCH, homeSearch)
            }
            ActivityUtils.startActivity(bundle, TrendDetailsActivity::class.java)
        }

    }


    private val mTrendSharePopup: TrendSharePopup by lazy {
        TrendSharePopup(context = this, onClick = {

        })
    }

    private val mTitle: String?
        get() = intent?.extras?.getString(EXTRA_KEY_TITLE)

    private val mTrendData: TrendData? by lazy {
        intent?.extras?.getSerializable(EXTRA_KEY_TREND) as? TrendData
    }

    private val mTrendData1: TrendData1? by lazy {
        intent?.extras?.getSerializable(EXTRA_KEY_TREND1) as? TrendData1
    }

    private val mHomeSearch: HomeSearch? by lazy {
        intent?.extras?.getSerializable(EXTRA_KEY_SEARCH) as? HomeSearch
    }

    override fun viewModel(): SameViewModel {
        return createViewModel()
    }

    override val layoutResId: Int
        get() = R.layout.activity_details_trend

    override fun stateBar(): StatusBar {
        return StatusBar(isLightMode = true, view = flTrendDetailsBar)
    }

    override fun initView() {

        flTrendDetailsBar.setOnClickRightTextView(onClick = {
            mTrendSharePopup.showPopupWindow()
        })

        wvTrendDetailsWeb.webViewClient = WebViewClient()
        wvTrendDetailsWeb.settings.apply {
            //支持缩放，默认为true。
            setSupportZoom(false)
            //调整图片至适合webview的大小
            useWideViewPort = true
            // 缩放至屏幕的大小
            loadWithOverviewMode = true
            //设置默认编码
            defaultTextEncodingName = "utf-8"
            //设置自动加载图片
            loadsImagesAutomatically = true
            //允许访问文件
            allowFileAccess = true
            //开启javascript
            javaScriptEnabled = true
            //支持通过JS打开新窗口
            javaScriptCanOpenWindowsAutomatically = true
            //支持内容重新布局
            layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN;
            //关闭webview中缓存
            cacheMode = WebSettings.LOAD_CACHE_ELSE_NETWORK
        }
        mTrendData?.let { trendData ->

            tvTrendDetailsTitle.text = trendData.title
            tvTrendDetailsTime.text = trendData.create_time
            tvTrendDetailsType.text = trendData.type
            val tagColor = when (trendData.type) {
                "联盟新闻" -> R.color.FF_2F6CFA
                "通知公告" -> R.color.FF_E24141
                else -> R.color.FF_FA922F
            }
            tvTrendDetailsType.setTextColor(ColorUtils.getColor(tagColor))
            val tagsBackground = when (trendData.type) {
                "联盟新闻" -> R.drawable.bg_radius_02dp_trend_1
                "通知公告" -> R.drawable.bg_radius_02dp_trend_2
                else -> R.drawable.bg_radius_02dp_trend_3
            }
            tvTrendDetailsType.setBackgroundResource(tagsBackground)
        }
        mTrendData1?.let { trendData ->
            tvTrendDetailsTitle.text = trendData.title
            tvTrendDetailsTime.text = "${trendData.years}/${trendData.day}"
            tvTrendDetailsType.text = trendData.type
            val tagColor = when (trendData.type) {
                "联盟新闻" -> R.color.FF_2F6CFA
                "通知公告" -> R.color.FF_E24141
                else -> R.color.FF_FA922F
            }
            tvTrendDetailsType.setTextColor(ColorUtils.getColor(tagColor))
            val tagsBackground = when (trendData.type) {
                "联盟新闻" -> R.drawable.bg_radius_02dp_trend_1
                "通知公告" -> R.drawable.bg_radius_02dp_trend_2
                else -> R.drawable.bg_radius_02dp_trend_3
            }
            tvTrendDetailsType.setBackgroundResource(tagsBackground)
        }
        mHomeSearch?.let { trendData ->
            tvTrendDetailsTitle.text = trendData.title
            tvTrendDetailsTime.text = trendData.create_time
            tvTrendDetailsType.text = trendData.type
            val tagColor = when (trendData.type) {
                "联盟新闻" -> R.color.FF_2F6CFA
                "通知公告" -> R.color.FF_E24141
                else -> R.color.FF_FA922F
            }
            tvTrendDetailsType.setTextColor(ColorUtils.getColor(tagColor))
            val tagsBackground = when (trendData.type) {
                "联盟新闻" -> R.drawable.bg_radius_02dp_trend_1
                "通知公告" -> R.drawable.bg_radius_02dp_trend_2
                else -> R.drawable.bg_radius_02dp_trend_3
            }
            tvTrendDetailsType.setBackgroundResource(tagsBackground)
        }
    }

    override fun initData() {
        mTrendData?.let {
            viewModel.sameTrendDetails(it.id)
        }
        mTrendData1?.let {
            viewModel.sameTrendDetails(it.id)
        }
        mHomeSearch?.let {
            viewModel.sameTrendDetails(it.id)
        }
    }

    override fun initViewMode() {
        viewModel.trendDetailsLiveData.observe(this as LifecycleOwner, { response ->
            if (response.status != Status.SUCCESS) {
                return@observe
            }
            val data = response.data?.data
                ?: return@observe
            fillData(data)
        })
    }

    private fun fillData(trendDetails: TrendDetails) {

        val document: Document = Jsoup.parse(trendDetails.content)
        val elements: Elements = document.select("img")
        val span: Elements = document.select("span")
        elements.forEach {
            val style = "${it.attr("style")}width:100%;"
            it.attr("style", style)
        }
        span.forEach {
            val style = it.attr("style") + "font-size: 45px;"
            it.attr("style", style)
        }
        val realContent = buildString {
            append("<!DOCTYPE html><html><head><meta charset=\"utf-8\"></head><body>")
            append(document.body().toString())
            append("</body></html>")
        }
        wvTrendDetailsWeb.loadDataWithBaseURL("", realContent, "text/html", "utf-8", null)

//        val document: Document = Jsoup.parse(trendData.content)
//        val elements: Elements = document.select("img")
//        elements.forEach {
//            val style = "${it.attr("style")}width:100%;"
//            it.attr("style", style)
//        }
//        val realContent = buildString {
//            append("<!DOCTYPE html><html><head><meta charset=\"utf-8\"></head><body>")
//            append(document.body().toString())
//            append("</body></html>")
//        }
//        Markwon.builder(this)
//            .usePlugin(HtmlPlugin.create())
//            .usePlugin(GlideImagesPlugin.create(this))
//            .usePlugin(GlideImagesPlugin.create(Glide.with(this)))
//            .usePlugin(GlideImagesPlugin.create(object : GlideImagesPlugin.GlideStore {
//                override fun load(drawable: AsyncDrawable): RequestBuilder<Drawable> {
//                    return Glide.with(this@TrendDetailsActivity)
//                        .load(drawable.destination)
//                }
//
//                override fun cancel(target: Target<*>) {
//                    //Glide.with(this@TrendDetailsActivity).clear(target)
//                }
//            }))
//            .build().setMarkdown(tvTrendDetailsContent, realContent)
    }

}